package cn.cat.ip2region;


import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;

import java.io.File;
import java.lang.reflect.Method;

public class IpUtil {

    private static IpUtil instance;

    public IpUtil() {
    }

    public static IpUtil getInstance() {
        if (instance == null)
            instance = new IpUtil();
        return instance;
    }

    /**
     *
     * @param ip
     * @return 国家|地区|省份|城市|IPS
     */
    public RegionEntity getCityInfo(String ip) {

        String dbPath = IpUtil.class.getResource("/ip2region.db").getPath();
//        String dbPath = "/raid/fz/ip2region.db";
//        String dbPath = "hdfs://yview/application/offline/dns/lib/ip2region.db";
//        String dbPath = "/raid/fz/ip2region.db";//IpUtil.class.getResource("/ip2region.db").getPath();

        File file = new File(dbPath);
        if (file.exists() == false) {
            System.out.println("Error: Invalid ip2region.db file");
        }

        //查询算法
        int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
        try {
            DbConfig config = new DbConfig();
            DbSearcher searcher = new DbSearcher(config, dbPath);
            //define the method
            Method method = null;
            switch (algorithm) {
                case DbSearcher.BTREE_ALGORITHM:
                    method = searcher.getClass().getMethod("btreeSearch", String.class);
                    break;
                case DbSearcher.BINARY_ALGORITHM:
                    method = searcher.getClass().getMethod("binarySearch", String.class);
                    break;
                case DbSearcher.MEMORY_ALGORITYM:
                    method = searcher.getClass().getMethod("memorySearch", String.class);
                    break;
            }

            DataBlock dataBlock = null;
            if (Util.isIpAddress(ip) == false) {
                System.out.println("Error: Invalid ip address");
            }

            dataBlock = (DataBlock) method.invoke(searcher, ip);
            searcher.close();
            return getRegionEntity(dataBlock.getRegion());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public RegionEntity getRegionEntity(String str){
        if (str==null || "".equals(str)){
            return null;
        }
        String[] strings = str.split("\\|");
        return new RegionEntity(strings[0],strings[1],strings[2],strings[3],strings[4]);
    }





}
